import Router from 'koa-router'

// import axios from '../util/axios'
import Menu from '../db/models/Menu'
import Province from '../db/models/Province'
import City from '../db/models/City'

const router = new Router({ prefix: '/geo' })

router.get('/getPosition', async ctx => {
  const { req } = ctx
  // const ip =
  //   req.headers['x-forwarded-for'] ||
  //   req.connection.remoteAddress ||
  //   req.socket.remoteAddress ||
  //   req.connection.socket.remoteAddress
  //
  // const res = await axios.get(
  //   'http://ip.taobao.com/service/getIpInfo.php?ip=60.217.196.124'
  // )
  //
  // console.log(res.data)

  ctx.body = {
    code: 0,
    provinces: '山东',
    city: '济南'
  }
})

router.get('/menu', async ctx => {
  const { menu } = await Menu.findOne()
  ctx.body = {
    menu
  }
})

router.get('/province', async ctx => {
  const province = await Province.find()
  ctx.body = {
    code: 0,
    provinceList: province.map(({ id, value }) => ({ id, label: value }))
  }
})

router.get('/province/:pid', async ctx => {
  const { value } = await City.findOne({ id: ctx.params.pid })
  ctx.body = {
    code: 0,
    city: value.map(({ id, name, province }) => ({ id, label: name, province }))
  }
})

router.get('/cities', async ctx => {
  let city = []
  const cities = await City.find()
  city = cities.reduce((city, { value }) => city.concat(value), city)
  ctx.body = {
    code: 0,
    cities: city.map(({ province, name, id }) => ({
      province,
      id,
      name: name === '市辖区' || name === '省直辖县级行政区划' ? province : name
    }))
  }
})

router.get('/hotCity', ctx => {
  let list = [
    '北京市',
    '上海市',
    '广州市',
    '深圳市',
    '天津市',
    '西安市',
    '杭州市',
    '南京市',
    '武汉市',
    '成都市'
  ]
  ctx.body = {
    code: 0,
    list
  }
})

export default router
